
package es.unileon.is.finalproyect.adminInterface;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.List;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;

import es.unileon.is.finalproyect.auxiliar.Streams;
import es.unileon.is.finalproyect.dbconnection.ApplicationConnection;
import es.unileon.is.finalproyect.exceptions.DatabaseException;
import es.unileon.is.finalproyect.exceptions.UniqueException;
import es.unileon.is.finalproyect.texts.*;
import es.unileon.is.finalproyect.themes.Themes;
import es.unileon.is.finalproyect.userinterface.ViewHelp;
import es.unileon.is.finalproyect.users.*;

public class AdminInterface extends JFrame {

	private ButtonGroup _gr;
	private Map<JButton,User> _jbuttonUserMapAU;
	private List<Group> _listGroup;
	private List<User> _listUser;
	private User _adminUser;
	String _options[] = {"Accept new user", "Add user to group",
			"Delete user", "Give administrator privileges",
			"Upload new text", "Revise groups", "Backup",
			"Assign texts", "Delete texts"};
	
	JPanel _rightPanel;
	
	File _textFile;
	File _questionsFile;
	private String[] _groupsReviseGroups;
	private List<Group> _listReviseGroups;
	private JComboBox<String> _comboBox;
	private JComboBox<String> _comboRevise;
	private JComboBox<String> _comboDelete;
	private JComboBox<String> _comboAssignTextToGroup;
	private JComboBox<String> _comboAssignTextToUser;
	private Map<JCheckBox, User> _jcheckUserMapAG;
	private Map<JCheckBox, User> _jcheckUserMapDU;
	private Map<JCheckBox, User> _jcheckUserMapDA;
	private Map<JCheckBox, Text> _jcheckTextMapAT;
	private Map<JCheckBox, Text> _jcheckTextMapDT;
	private JTextField _txtCreateButton;
	
	JTextFieldInt _timeRead;
	JTextFieldInt _timeAnswer;
	/**
	 * Create the frame.
	 */
	public AdminInterface(User adminUser) {
		_adminUser=adminUser;
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setExtendedState(JFrame.MAXIMIZED_BOTH);
		initComponents();
		
	}
	
	
	private void initComponents(){
		
		//*****modificaciones para JAVAHELP*******
		JMenuBar menuBar = new JMenuBar();
		//*********** MODIFICACIONES THEME *******************
		JMenu menuthemes = new JMenu("Themes");
		menuthemes = Themes.showNewTheme(menuthemes, getContentPane());
		menuBar.add(menuthemes);
		//****************************************************
		JMenu menuHelp = new JMenu("Help");
		JMenuItem help = new JMenuItem("Show help");
		menuBar.add(Box.createHorizontalGlue());
		menuBar.add(menuHelp);
		menuHelp.add(help);
		setJMenuBar(menuBar);
		//metodo para dar la accion a help
		ViewHelp.showHelp(help, getContentPane(), "ventana_Admin");
		//*****************************************
		
		getContentPane().setLayout(new GridLayout(1,2));
		JPanel leftPanel = new JPanel();
		leftPanel.setLayout(new BorderLayout());
		getContentPane().add(leftPanel);
		
		
		JLabel title = new JLabel("What do you want to do?",JLabel.CENTER);
		leftPanel.add(title,BorderLayout.NORTH);
		
		
		_gr = new ButtonGroup();		
		ActionListener al = new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				showRightPane();
			}
		};
		
		JPanel centralPanel = new JPanel();
		leftPanel.add(centralPanel, BorderLayout.CENTER);
		centralPanel.setLayout(new BoxLayout(centralPanel, BoxLayout.X_AXIS));
		centralPanel.add(Box.createHorizontalGlue());
		JPanel buttonPanel = new JPanel();
		centralPanel.add(buttonPanel, BorderLayout.CENTER);
		centralPanel.add(Box.createHorizontalGlue());
		buttonPanel.setLayout(new BoxLayout(buttonPanel,BoxLayout.Y_AXIS));
		buttonPanel.add(Box.createVerticalGlue());
		for(int i = 0; i < _options.length; i++){
			JRadioButton button = new JRadioButton(_options[i]);
			buttonPanel.add(button);
			_gr.add(button);
			button.addActionListener(al);
		}
		buttonPanel.add(Box.createVerticalGlue());
		_rightPanel = new JPanel();
		getContentPane().add(_rightPanel);
		pack();
	}
	
	// This method returns the selected radio button in a button group
	private static JRadioButton getSelection(ButtonGroup group) {
	    for (Enumeration<AbstractButton> e=group.getElements(); e.hasMoreElements(); ) {
	        JRadioButton b = (JRadioButton)e.nextElement();
	        if (b.getModel() == group.getSelection()) {
	            return b;
	        }
	    }
	    return null;
	}
	
	private void showRightPane(){
		String name = getSelection(_gr).getText();
		getContentPane().remove(_rightPanel);
		_rightPanel = null;	
		if(name.equals(_options[0])){
			_rightPanel = paneAcceptUser();			
		} else if(name.equals(_options[1])){
			_rightPanel = paneAddUserGroup();			
		} else if(name.equals(_options[2])){
			_rightPanel = paneDeleteUser();		
		} else if(name.equals(_options[3])){
			_rightPanel = paneDoAdministrator();			
		} else if(name.equals(_options[4])){
			_rightPanel = paneUploadText();			
		} else if(name.equals(_options[5])){
			_rightPanel = paneReviseGroups();
		} else if(name.equals(_options[6])){
			_rightPanel = paneBackup();
		} else if(name.equals(_options[7])){
			_rightPanel = paneAssignTexts();
		} else if(name.equals(_options[8])){
			_rightPanel = paneDeleteTexts();
		}
		
		getContentPane().add(_rightPanel);
		
		revalidate();
		repaint();
	}
	
	private JPanel paneAcceptUser(){
		
		JPanel returnPanel = new JPanel(new BorderLayout());
		JPanel innerPanel = new JPanel(null);
		JScrollPane scroll = new JScrollPane(innerPanel);
		returnPanel.add(scroll,BorderLayout.CENTER);
		List<User> list = _adminUser.getPendingUsers();
		
		_jbuttonUserMapAU = new HashMap<JButton,User>();
		
		ActionListener ac = new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				_jbuttonUserMapAU.get((JButton)evt.getSource()).changeType(_adminUser, "REGULAR");
				showRightPane();
			}
		};
		int y = 10;
		for(User user: list){
			JLabel name = new JLabel(user.getEmail());
			JButton button = new JButton("Accept");
			button.addActionListener(ac);
			int buttonWidth = (int)button.getPreferredSize().getWidth();
			int buttonHeight = (int)button.getPreferredSize().getHeight();
			button.setBounds(10,y,buttonWidth, buttonHeight);
			int nameWidth = (int)name.getPreferredSize().getWidth();
			int nameHeight = (int) name.getPreferredSize().getHeight();
			name.setBounds(buttonWidth+20,y+(buttonHeight-nameHeight)/2,nameWidth,nameHeight);
			y+= buttonHeight + 20;
			innerPanel.add(name);
			innerPanel.add(button);
			_jbuttonUserMapAU.put(button, user);
		}
		innerPanel.setPreferredSize(new Dimension(400,y));
		
		return returnPanel;
	}
	
	private JPanel paneAddUserGroup(){
		JPanel returnPanel = new JPanel(new BorderLayout());
		JPanel innerPanel = new JPanel(null);
		JScrollPane scroll = new JScrollPane(innerPanel);
		returnPanel.add(scroll, BorderLayout.CENTER);
		
		_jcheckUserMapAG = new HashMap<JCheckBox,User>();
		List<User> list = _adminUser.requestAllAceptedUsers();

		int y = 10;
		for(User u:list){
			JCheckBox box = new JCheckBox(u.getEmail());
			int boxWidth = (int)box.getPreferredSize().getWidth();
			int boxHeight = (int)box.getPreferredSize().getHeight();
			box.setBounds(10,y,boxWidth, boxHeight);
			y+=boxHeight + 20;
			innerPanel.add(box);
			_jcheckUserMapAG.put(box, u);			
		}
		
		innerPanel.setPreferredSize(new Dimension(400,y));
		
		JPanel southPanel = new JPanel(new GridLayout(1,2));
		returnPanel.add(southPanel, BorderLayout.SOUTH);
		
		_listGroup = Group.requestAllGroups(_adminUser);
		String[] names = new String[_listGroup.size()];
		int i = 0;
		for(Group g:_listGroup){
			names[i]=(g.getName());
			i++;
		}
		_comboBox = new JComboBox<String>();
		_comboBox.setModel(new DefaultComboBoxModel<String>(names));
		_comboBox.setMaximumRowCount(2);
		southPanel.add(_comboBox);
		
		JButton addButton = new JButton("Assign");
		southPanel.add(addButton);
		addButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				
				Group groupToMove = _listGroup.get(_comboBox.getSelectedIndex());
				for(Map.Entry<JCheckBox, User> entry : _jcheckUserMapAG.entrySet()){
					if(entry.getKey().isSelected()){
						groupToMove.assignUser(_adminUser, entry.getValue());
					}
				}
				JOptionPane.showMessageDialog(getContentPane(), "User(s) added", "Information", JOptionPane.INFORMATION_MESSAGE);

			}
		});
		
		return returnPanel;
	}
	
	private JPanel paneDeleteUser(){
		JPanel returnPanel = new JPanel(new BorderLayout());
		JPanel innerPanel = new JPanel(null);
		JScrollPane scroll = new JScrollPane(innerPanel);
		returnPanel.add(scroll, BorderLayout.CENTER);
		
		
		_jcheckUserMapDU = new HashMap<JCheckBox,User>();
		List<User> list = _adminUser.requestAllAceptedUsers();

		int y = 10;
		for(User u:list){
			JCheckBox box = new JCheckBox(u.getEmail());
			int boxWidth = (int)box.getPreferredSize().getWidth();
			int boxHeight = (int)box.getPreferredSize().getHeight();
			box.setBounds(10,y,boxWidth, boxHeight);
			y+=boxHeight + 20;
			innerPanel.add(box);
			_jcheckUserMapDU.put(box, u);			
		}
		
		innerPanel.setPreferredSize(new Dimension(400,y));
		
		JButton addButton = new JButton("Delete");
		returnPanel.add(addButton, BorderLayout.SOUTH);
		addButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				for(Map.Entry<JCheckBox, User> entry : _jcheckUserMapDU.entrySet()){
					if(entry.getKey().isSelected()){
						entry.getValue().deleteUser(_adminUser);
					}
				}
				showRightPane();
			}
		});
		
		return returnPanel;
	}
	
	private JPanel paneDoAdministrator(){
		JPanel returnPanel = new JPanel(new BorderLayout());
		JPanel innerPanel = new JPanel(null);
		JScrollPane scroll = new JScrollPane(innerPanel);
		returnPanel.add(scroll, BorderLayout.CENTER);
		
		
		_jcheckUserMapDA = new HashMap<JCheckBox,User>();
		List<User> list = _adminUser.requestAllAceptedUsers();

		int y = 10;
		for(User u:list){
			JCheckBox box = new JCheckBox(u.getEmail());
			int boxWidth = (int)box.getPreferredSize().getWidth();
			int boxHeight = (int)box.getPreferredSize().getHeight();
			box.setBounds(10,y,boxWidth, boxHeight);
			y+=boxHeight + 20;
			innerPanel.add(box);
			_jcheckUserMapDA.put(box, u);			
		}
		
		innerPanel.setPreferredSize(new Dimension(400,y));
		
		JPanel southPanel = new JPanel(new GridLayout(1,2));
		returnPanel.add(southPanel, BorderLayout.SOUTH);
		
		JButton addButton = new JButton("Do administrator");
		southPanel.add(addButton);
		addButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				for(Map.Entry<JCheckBox, User> entry : _jcheckUserMapDA.entrySet()){
					if(entry.getKey().isSelected()){
						entry.getValue().changeType(_adminUser,"ADMINISTRATOR");
					}
				}

				showRightPane();
			}
		});
		
		return returnPanel;
	}
	
	private JPanel paneUploadText(){
		JPanel returnPanel = new JPanel(new GridLayout(5,1));
		
		JPanel firstPanel = new JPanel(new FlowLayout());
		JLabel labelT = new JLabel("Upload new Text");
		JButton buttonT = new JButton("Browse");
		buttonT.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				_textFile = getFile();
			}
		});
		firstPanel.add(labelT);
		firstPanel.add(buttonT);
		returnPanel.add(firstPanel);
		
		JPanel secondPanel = new JPanel(new FlowLayout());		
		JLabel labelQ = new JLabel ("Upload new Question");
		JButton buttonQ = new JButton("Browse");
		buttonQ.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				_questionsFile = getFile();
			}
		});
		secondPanel.add(labelQ);
		secondPanel.add(buttonQ);
		returnPanel.add(secondPanel);
		
		JPanel thirdPanel = new JPanel(new FlowLayout());
		_timeRead = new JTextFieldInt();
		_timeRead.setPreferredSize(new Dimension(50, 25));
		JLabel timeRT= new JLabel("Time to Read (in minutes)");
		thirdPanel.add(_timeRead);
		thirdPanel.add(timeRT);
		returnPanel.add(thirdPanel);
		
		JPanel fourthPanel = new JPanel(new FlowLayout());
		_timeAnswer = new JTextFieldInt();
		_timeAnswer.setPreferredSize(new Dimension(50, 25));
		JLabel timeA= new JLabel("Time to Answer (in minutes)");
		fourthPanel.add(_timeAnswer);
		fourthPanel.add(timeA);
		returnPanel.add(fourthPanel);
		
		JPanel fifthPanel = new JPanel(new FlowLayout());
		JButton accept = new JButton("Accept");
		accept.setPreferredSize(new Dimension(100, 60));
		fifthPanel.add(accept);
		returnPanel.add(fifthPanel);

		accept.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				uploadText();
			}
		});
		
		return returnPanel;
	}
	
	private File getFile(){
		JFileChooser fileChooser=new JFileChooser();
        Component temporaryLostComponent = null;
        int seleccion = fileChooser.showOpenDialog(temporaryLostComponent) ;
        if (seleccion == JFileChooser.APPROVE_OPTION){ 
	        String ruta= fileChooser.getSelectedFile().getAbsolutePath(); 
			return new File(ruta);
        } else {
        	return null;
        }
	}
	
	private void uploadText(){
		try {
			Scanner scan = new Scanner(_questionsFile);
			int i = 0;
			for(;scan.hasNext();i++){
				scan.nextLine();
			}
			if(i < 10){
				String msg = "There are less than 10 questions in that file. Please, write 10 or more questions";
				JOptionPane.showMessageDialog(this, msg, "Error" , JOptionPane.ERROR_MESSAGE);
				return;
			} else {
				scan = new Scanner(_questionsFile);
				String[] questions = new String[i];
				String[][] answers = new String[i][4];
				String msg = "Correct sintax: \"Question\"|\"Correct answer\"|\"Wrong answer #1\"|\"Wrong answer #2\"|\"Wrong answer #2\"";
				for(int j = 0; j < i && scan.hasNext(); j++){
					StringTokenizer lineTokenizer = new StringTokenizer(scan.nextLine(),"|");
					if(lineTokenizer.hasMoreTokens()){
						questions[j] = lineTokenizer.nextToken();
					}
					if(lineTokenizer.hasMoreTokens()){
						answers[j][0] = lineTokenizer.nextToken();
					}
					if(lineTokenizer.hasMoreTokens()){
						answers[j][1] = lineTokenizer.nextToken();
					}
					if(lineTokenizer.hasMoreTokens()){
						answers[j][2] = lineTokenizer.nextToken();
					}
					if(lineTokenizer.hasMoreTokens()){
						answers[j][3] = lineTokenizer.nextToken();
						continue;
					}
					String errorMsg = "Incorrect sintax for question number " + (j+1) +". " + msg;
					JOptionPane.showMessageDialog(this, errorMsg, "Error" , JOptionPane.ERROR_MESSAGE);
					return;
				}
				String textName = _textFile.getName();
				byte[] data = Streams.inputStreamToByteArray(new FileInputStream(_textFile));
				int secondsToRead = Integer.parseInt(_timeRead.getText()) * 60;
				int secondsToAnswer = Integer.parseInt(_timeAnswer.getText()) * 60;
				try{
					Text t = new Text(_adminUser, textName, data, secondsToRead, secondsToAnswer);
					int textID = t.getID();
					for(int j = 0; j < i; j++){
						new Question(_adminUser, textID, questions[j], answers[j]);
					}
					JOptionPane.showMessageDialog(this, "Text and questions succesfully uploaded", "Information", JOptionPane.INFORMATION_MESSAGE);
			
				} catch (UniqueException e){
					JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
				}
			}
		} catch (FileNotFoundException e) {
			JOptionPane.showMessageDialog(this, e.getMessage(), "Error" , JOptionPane.ERROR_MESSAGE);
		}
		
	}
	
	private JPanel paneReviseGroups(){
		JPanel returnPanel = new JPanel(new GridLayout(3,1));	
		_comboRevise = new JComboBox<String>();
		_listReviseGroups = Group.requestAllGroups(_adminUser);
		_groupsReviseGroups = new String[_listReviseGroups.size()];
		int i = 0;
		for(Group g:_listReviseGroups){
			_groupsReviseGroups[i]=g.getName();
			i++;
		}		
		_comboRevise.setModel(new DefaultComboBoxModel<String>(_groupsReviseGroups));
		_comboRevise.setMaximumRowCount(5);
		_comboRevise.setPreferredSize(new Dimension(100,25));
		
		_comboDelete = new JComboBox<String>();	
		_comboDelete.setModel(new DefaultComboBoxModel<String>(_groupsReviseGroups));
		_comboDelete.setMaximumRowCount(5);
		_comboDelete.setPreferredSize(new Dimension(100,25));
		
		JPanel firstPanel = new JPanel(new FlowLayout());
		JButton reviseButton = new JButton("Revise");
		firstPanel.add(reviseButton);
		firstPanel.add(_comboRevise);
		
		JPanel secondPanel = new JPanel(new FlowLayout());
		JButton deleteButton = new JButton("Delete");
		secondPanel.add(deleteButton);
		secondPanel.add(_comboDelete);
		
		JPanel thirdPanel = new JPanel(new FlowLayout());
		JButton createButton = new JButton("Create");
		_txtCreateButton = new JTextField("Insert name");
		_txtCreateButton.addFocusListener(new FocusAdapter(){
			public void focusGained(FocusEvent evt){
				((JTextField)evt.getSource()).selectAll();
			}
		});
		thirdPanel.add(_txtCreateButton);
		thirdPanel.add(createButton);
		
		returnPanel.add(firstPanel);
		returnPanel.add(secondPanel);
		returnPanel.add(thirdPanel);
		
		reviseButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				JDialog dialog = new JDialog();
				dialog.setTitle(_groupsReviseGroups[_comboRevise.getSelectedIndex()]);
				Group g = _listReviseGroups.get(_comboRevise.getSelectedIndex());
				JPanel namesPanel = new JPanel(null);
				JScrollPane scroll = new JScrollPane(namesPanel);
				dialog.add(scroll);
				dialog.setSize(new Dimension(400,400));
				dialog.setVisible(true);
				int y = 10;
				for(int i=0;i<g.getAssignedUsers().size();i++){
					JLabel name = new JLabel(g.getAssignedUsers().get(i).getName()+" "+g.getAssignedUsers().get(i).getSurname()+" ("+g.getAssignedUsers().get(i).getEmail()+")");
					name.setBounds(10,y,300,30);
					y+=40;
					namesPanel.add(name);
				}

				showRightPane();
			}
		});
		
		deleteButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				int i = _comboDelete.getSelectedIndex();
				Group g = _listReviseGroups.get(i);
				g.deleteGroup(_adminUser);
				showRightPane();
			}
		});
		
		createButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				try{
					new Group(_adminUser,_txtCreateButton.getText());
					showRightPane();
				} catch (UniqueException e){
					JOptionPane.showMessageDialog(getContentPane(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		
		return returnPanel;
	}
	
	private JPanel paneBackup(){
		JPanel returnPanel = new JPanel();
		returnPanel.setLayout(new BoxLayout(returnPanel,BoxLayout.Y_AXIS));
		JButton makeBackupButton = new JButton("Make backup");
		makeBackupButton.setPreferredSize(new Dimension(100,50));
		makeBackupButton.setAlignmentX(Component.CENTER_ALIGNMENT);
		makeBackupButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				makeBackup();
			}
		});
		returnPanel.add(Box.createVerticalGlue());
		returnPanel.add(makeBackupButton);
		JButton restoreBackupButton = new JButton("Restore backup");
		restoreBackupButton.setPreferredSize(new Dimension(100,50));
		restoreBackupButton.setAlignmentX(Component.CENTER_ALIGNMENT);
		restoreBackupButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				restoreBackup();
			}
		});
		returnPanel.add(Box.createRigidArea(new Dimension(0,20)));
		returnPanel.add(restoreBackupButton);
		returnPanel.add(Box.createVerticalGlue());

		return returnPanel;
	}
	
	private void makeBackup(){
		String adviseMsg = "This function only works if you have run the program as an administrator. �Did you?";
		int option = JOptionPane.showConfirmDialog(this, adviseMsg, "Question", JOptionPane.YES_NO_OPTION);
		if(option == JOptionPane.NO_OPTION){
			String msg = "Sorry, in that case you can not make the backup";
			JOptionPane.showMessageDialog(this, msg, "Sorry", JOptionPane.INFORMATION_MESSAGE);
		} else {
			new Thread(){
				public void run(){
					if(SwingUtilities.isEventDispatchThread()){
						JOptionPane.showMessageDialog(getContentPane(), "Please wait while the backup is being done", "Please wait", JOptionPane.PLAIN_MESSAGE);
					} else try {
						SwingUtilities.invokeAndWait(new Runnable(){
							public void run(){
								JOptionPane.showMessageDialog(getContentPane(), "Please wait while the backup is being done", "Please wait", JOptionPane.PLAIN_MESSAGE);
							}
						});
					}catch (InvocationTargetException e) {
						e.printStackTrace();
					} catch (InterruptedException e){
						e.printStackTrace();
					}
				}
			}.start();
			try {
				ApplicationConnection.makeBackup(_adminUser);
				String msg = "Backup has been done. Now, select a directory to save the backup and the log file";
				JOptionPane.showMessageDialog(this, msg, "Information", JOptionPane.INFORMATION_MESSAGE);
				JFileChooser fileChooser=new JFileChooser();
				fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		        Component temporaryLostComponent = null;
		        int seleccion = fileChooser.showOpenDialog(temporaryLostComponent) ;
		        if (seleccion == JFileChooser.APPROVE_OPTION){ 
			        String ruta= fileChooser.getSelectedFile().getAbsolutePath();
			        new Thread(){
						public void run(){
							if(SwingUtilities.isEventDispatchThread()){
								JOptionPane.showMessageDialog(getContentPane(), "Files are being moved", "Please wait", JOptionPane.PLAIN_MESSAGE);
							} else try {
								SwingUtilities.invokeAndWait(new Runnable(){
									public void run(){
										JOptionPane.showMessageDialog(getContentPane(), "Files are being moved", "Please wait", JOptionPane.PLAIN_MESSAGE);									}
								});
							}catch (InvocationTargetException e) {
								e.printStackTrace();
							} catch (InterruptedException e){
								e.printStackTrace();
							}
						}
					}.start();
					ApplicationConnection.moveBackupTo(_adminUser, ruta + (System.getProperty("os.name").equals("Linux")?"/":"\\"));
					JOptionPane.showMessageDialog(this, "Now you can find the backup in that directory", "Information", JOptionPane.INFORMATION_MESSAGE);
		        }
			} catch (DatabaseException e){
				JOptionPane.showMessageDialog(getContentPane(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	
	private void restoreBackup(){
		String adviseMsg = "This function only works if you have run the program as an administrator. �Did you?";
		int option = JOptionPane.showConfirmDialog(this, adviseMsg, "Question", JOptionPane.YES_NO_OPTION);
		if(option == JOptionPane.NO_OPTION){
			String msg = "Sorry, in that case you can not restore a backup";
			JOptionPane.showMessageDialog(this, msg, "Sorry", JOptionPane.INFORMATION_MESSAGE);
		} else {
			JOptionPane.showMessageDialog(this, "Please, select the backup", "Information", JOptionPane.INFORMATION_MESSAGE);
			JFileChooser fileChooser=new JFileChooser();
			fileChooser.setFileFilter(new FileFilter(){
				public boolean accept(File f){
					if(f.isDirectory()){
					    return true;
					}
					String nombre = f.getName().toLowerCase();
					if(nombre != null){
					    if(nombre.endsWith(".dmp")){
					    	return true;
					    }
					}
					return false;
			   	}
				public String getDescription(){
					return "Oracle Dump File";
			   }
			});
			
	        int seleccion = fileChooser.showOpenDialog(this) ;
	        if (seleccion == JFileChooser.APPROVE_OPTION){ 
		        String backupName = fileChooser.getSelectedFile().getAbsolutePath();
		        new Thread(){
					public void run(){
						JOptionPane.showMessageDialog(getContentPane(), "Please wait while the backup is being restored", "Please wait", JOptionPane.PLAIN_MESSAGE);
					}
				}.start();
				try{
					ApplicationConnection.restoreBackup(_adminUser, backupName);
					JOptionPane.showMessageDialog(this, "The backup has been restored", "Information", JOptionPane.INFORMATION_MESSAGE);
				} catch (DatabaseException e){
					JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
				}
	        }
		}
	}
	
	private JPanel paneAssignTexts(){
		JPanel returnPanel = new JPanel(new BorderLayout());
		JPanel innerPanel = new JPanel(null);
		JScrollPane scroll = new JScrollPane(innerPanel);
		returnPanel.add(scroll, BorderLayout.CENTER);
		
		_jcheckTextMapAT = new HashMap<JCheckBox,Text>();
		List<Text> list = Text.requestAllTexts(_adminUser);

		int y = 10;
		for(Text t:list){
			JCheckBox box = new JCheckBox(t.getTitle());
			int boxWidth = (int)box.getPreferredSize().getWidth();
			int boxHeight = (int)box.getPreferredSize().getHeight();
			box.setBounds(10,y,boxWidth, boxHeight);
			y+=boxHeight + 20;
			innerPanel.add(box);
			_jcheckTextMapAT.put(box, t);			
		}
		
		innerPanel.setPreferredSize(new Dimension(400,y));
		
		JPanel southPanel = new JPanel(new GridLayout(1,4));
		returnPanel.add(southPanel, BorderLayout.SOUTH);
		
		_listGroup = Group.requestAllGroups(_adminUser);
		String[] names = new String[_listGroup.size()];
		int i = 0;
		for(Group g:_listGroup){
			names[i]=(g.getName());
			i++;
		}
		_comboAssignTextToGroup = new JComboBox<String>();
		_comboAssignTextToGroup.setModel(new DefaultComboBoxModel<String>(names));
		_comboAssignTextToGroup.setMaximumRowCount(2);
		southPanel.add(_comboAssignTextToGroup);
		
		JButton assignToGroupButton = new JButton("Assign to group");
		southPanel.add(assignToGroupButton);
		assignToGroupButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				
				Group groupToAssign = _listGroup.get(_comboAssignTextToGroup.getSelectedIndex());
				for(Map.Entry<JCheckBox, Text> entry : _jcheckTextMapAT.entrySet()){
					if(entry.getKey().isSelected()){
						groupToAssign.assignText(_adminUser, entry.getValue());
					}
				}
				JOptionPane.showMessageDialog(getContentPane(), "Text(s) assigned", "Information", JOptionPane.INFORMATION_MESSAGE);

			}
		});
		
		_listUser = _adminUser.requestAllAceptedUsers();
		names = new String[_listUser.size()];
		i = 0;
		for(User u : _listUser){
			names[i]=(u.getUserName());
			i++;
		}
		_comboAssignTextToUser = new JComboBox<String>();
		_comboAssignTextToUser.setModel(new DefaultComboBoxModel<String>(names));
		_comboAssignTextToUser.setMaximumRowCount(2);
		southPanel.add(_comboAssignTextToUser);
		
		JButton assignToUserButton = new JButton("Assign to user");
		southPanel.add(assignToUserButton);
		assignToUserButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				User userToAssign = _listUser.get(_comboAssignTextToUser.getSelectedIndex());
				for(Map.Entry<JCheckBox, Text> entry : _jcheckTextMapAT.entrySet()){
					if(entry.getKey().isSelected()){
						userToAssign.addPendingText(_adminUser, entry.getValue());
					}
				}
				JOptionPane.showMessageDialog(getContentPane(), "Text(s) assigned", "Information", JOptionPane.INFORMATION_MESSAGE);

			}
		});
		
		return returnPanel;
	}
	
	private JPanel paneDeleteTexts(){
		JPanel returnPanel = new JPanel(new BorderLayout());
		JPanel innerPanel = new JPanel(null);
		JScrollPane scroll = new JScrollPane(innerPanel);
		returnPanel.add(scroll, BorderLayout.CENTER);
		
		
		_jcheckTextMapDT = new HashMap<JCheckBox,Text>();
		List<Text> list = Text.requestAllTexts(_adminUser);

		int y = 10;
		for(Text t:list){
			JCheckBox box = new JCheckBox(t.getTitle());
			int boxWidth = (int)box.getPreferredSize().getWidth();
			int boxHeight = (int)box.getPreferredSize().getHeight();
			box.setBounds(10,y,boxWidth, boxHeight);
			y+=boxHeight + 20;
			innerPanel.add(box);
			_jcheckTextMapDT.put(box, t);			
		}
		
		innerPanel.setPreferredSize(new Dimension(400,y));
		
		JButton addButton = new JButton("Delete");
		returnPanel.add(addButton, BorderLayout.SOUTH);
		addButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent evt){
				for(Map.Entry<JCheckBox,Text> entry : _jcheckTextMapDT.entrySet()){
					if(entry.getKey().isSelected()){
						entry.getValue().deleteText(_adminUser);
					}
				}
				showRightPane();
			}
		});
		
		return returnPanel;
	}
 
}